package com.example.word.ui.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.example.word.MyApplication;
import com.example.dict.R;
import com.example.word.adapter.DictAdapter;
import com.example.word.bean.Dict;
import com.example.word.bean.User;
import com.example.word.bean.Word;
import com.example.word.ui.activity.AddActivity;
import com.example.word.ui.activity.AddWordActivity;
import com.example.word.ui.activity.LoginActivity;
import com.example.word.ui.activity.MainActivity;
import com.example.word.ui.activity.OpeningActivity;
import com.example.word.ui.activity.UnitActivity;
import com.example.word.util.CommonUtils;
import com.example.word.util.ExceptionUtils;
import com.example.word.util.HttpUtils;
import com.example.word.util.MessageUtils;
import com.example.word.util.SPUtils;
import com.example.word.util.StringUtils;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.tabs.TabLayout;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static android.app.Activity.RESULT_OK;


/**
 * 主页Fragment
 */

public class HomeFragment extends Fragment {

    public static List<String> state = Arrays.asList("0", "1", "2", "3");

    public static List<String> title = Arrays.asList("基础教育", "高等教育", "出国考试", "其他词汇");

    private String[] selectViews = new String[]{"新增词汇", "新增单词", "删除单词"};
    private int selectViewIndex;

    private Activity myActivity;//上下文
    private TabLayout tabTitle;
    private RecyclerView rvDictList;
    private DictAdapter dictAdapter;
    private LinearLayout llEmpty;
    private Boolean mIsAdmin;
    private String mAccount;//账号
    private FloatingActionButton btnAdd;
    private String typeId = "0";
    private List<Dict> dictList;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        myActivity = (Activity) context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        tabTitle = (TabLayout) view.findViewById(R.id.tab_title);
        rvDictList = (RecyclerView) view.findViewById(R.id.rv_dict_list);
        llEmpty = view.findViewById(R.id.ll_empty);
        btnAdd = (FloatingActionButton) view.findViewById(R.id.btn_add);
        //获取控件
        initView();
        //加号点击事件
        btnAdd.setOnClickListener(v -> {
            if ("".equals(mAccount)) {//未登录,跳转到登录页面
                MyApplication.Instance.getMainActivity().finish();
                startActivity(new Intent(myActivity, LoginActivity.class));
                return;
            }

            if (true) {
                //打开新增词汇页面
                Intent intent = new Intent(myActivity, AddActivity.class);
                startActivityForResult(intent, 100);
                return;
            }

            // 以下代码暂不会执行
            AlertDialog.Builder builder = new AlertDialog.Builder(myActivity);
            builder.setIcon(R.drawable.a1);//设置图标
            builder.setTitle("功能列表");//设置对话框的标题
            builder.setSingleChoiceItems(selectViews, 0, (dialog, which) -> {
                selectViewIndex = which;
            });
            builder.setPositiveButton("确定", (dialog, which) -> {
                if (selectViewIndex == 0) {
                    //打开新增词汇页面
                    Intent intent = new Intent(myActivity, AddActivity.class);
                    startActivityForResult(intent, 100);
                }
                if (selectViewIndex == 1) {
                    //打开新增单词页面
                    Intent intent = new Intent(myActivity, AddWordActivity.class);
                    startActivityForResult(intent, 100);
                }
                if (selectViewIndex == 2) {
                    //删除单词
                    Intent intent = new Intent(myActivity, AddWordActivity.class);
                    startActivityForResult(intent, 100);
                }
            }
            );
            builder.setNegativeButton("取消", (dialog, which) -> {
            });
            AlertDialog a = builder.create();
            a.show();
        });
        return view;
    }

    /**
     * 初始化页面
     */
    private void initView() {
        mIsAdmin = (Boolean) SPUtils.get(myActivity, SPUtils.IS_ADMIN, false);
        mAccount = (String) SPUtils.get(myActivity, SPUtils.ACCOUNT, "");
        btnAdd.setVisibility(mIsAdmin ? View.VISIBLE : View.GONE);
        tabTitle.setTabMode(TabLayout.MODE_SCROLLABLE);
        //设置tablayout距离上下左右的距离
        // tabTitle.setPadding(20,20,20,20);
        //为TabLayout添加tab名称
        for (int i = 0; i < title.size(); i++) {
            tabTitle.addTab(tabTitle.newTab().setText(title.get(i)));
        }

        LinearLayoutManager layoutManager = new LinearLayoutManager(myActivity);
        //=1.2、设置为垂直排列，用setOrientation方法设置(默认为垂直布局)
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //=1.3、设置recyclerView的布局管理器
        rvDictList.setLayoutManager(layoutManager);
        //==2、实例化适配器
        //=2.1、初始化适配器
        dictAdapter = new DictAdapter(llEmpty, rvDictList);
        //=2.3、设置recyclerView的适配器
        rvDictList.setAdapter(dictAdapter);
        loadData();
        dictAdapter.setItemListener(new DictAdapter.ItemListener() {
            @Override
            public void ItemClick(Dict dict) {
                boolean isAdmin = (boolean) SPUtils.get(myActivity, SPUtils.IS_ADMIN, false);
                String account = (String) SPUtils.get(myActivity, SPUtils.ACCOUNT, "");
                if ("".equals(account)) {//未登录,跳转到登录页面
                    MyApplication.Instance.getMainActivity().finish();
                    startActivity(new Intent(myActivity, LoginActivity.class));
                } else {//已经登录
                    Intent intent = null;
                    if (isAdmin) {
                        intent = new Intent(myActivity, AddActivity.class);
                        intent.putExtra("dict", dict);
                        startActivityForResult(intent, 100);
                    } else {
                        intent = new Intent(myActivity, UnitActivity.class);
                        intent.putExtra("wordCount", dict.getWordNumber());
                        intent.putExtra("dict", dict.getDict());
                        startActivityForResult(intent, 100);
                    }
                }
            }
        });
        tabTitle.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                typeId = state.get(tab.getPosition());
                loadData();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
    }

    //加载数据
    public void loadData(Activity... activities) {
        Map<String, String> requestParam = new HashMap<>();
        requestParam.put("typeId", typeId);
        // 调用 API 客户端的方法
        HttpUtils.sendGetRequest("/getDictList", requestParam, activities.length > 0 ? activities[0] : myActivity, Dict.class, response -> {
            dictList = response.getDataList();
            if (dictList != null && dictList.size() > 0) {
                rvDictList.setVisibility(View.VISIBLE);
                llEmpty.setVisibility(View.GONE);
                dictAdapter.addItem(dictList);
            } else {
                rvDictList.setVisibility(View.GONE);
                llEmpty.setVisibility(View.VISIBLE);
            }
        });
    }
    @Override
    public void onResume() {
        super.onResume();
        loadData();
    }
}
